<template>
  <ContainerGroup>
    <Container>
      <div class="query-box query-main">
        <!-- <div class="label">其他选项：</div> -->
        <div class="item-box">
          <div
            class="form-item"
            style="margin-left: 8px; margin-right: 56px; margin-bottom: 10px"
          >
            <span class="form-item-label">预约日期：</span>
            <el-date-picker
              v-model="ruleForm.timeDate"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd HH:mm:ss"
              :default-time="['00:00:00', '23:59:59']"
              size="mini"
            />
          </div>
          <!-- <div
            class="form-item"
            style="margin-left: 8px; margin-right: 56px; margin-bottom: 10px"
          >
            <span class="form-item-label">预出院日期：</span>
            <el-date-picker
              v-model="ruleForm.ycyDate"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd HH:mm:ss"
              :default-time="['00:00:00', '23:59:59']"
              size="mini"
            />
          </div> -->
          <!-- <div
            class="form-item"
            style="margin-left: 8px; margin-right: 56px; margin-bottom: 10px"
          >
            <span class="form-item-label">出院日期：</span>
            <el-date-picker
              v-model="ruleForm.cyDate"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd HH:mm:ss"
              :default-time="['00:00:00', '23:59:59']"
              size="mini"
            />
          </div> -->
          <div
            class="form-item"
            style="margin-left: 8px; margin-right: 56px; margin-bottom: 10px"
          >
            <span class="form-item-label">姓名：</span>
            <el-input
              v-model="ruleForm.patientName"
              placeholder="请输入姓名"
              size="mini"
            />
          </div>
          <div
            class="form-item"
            style="margin-left: 8px; margin-right: 56px; margin-bottom: 10px"
          >
            <span class="form-item-label">类型：</span>
            <el-select
              v-model="ruleForm.status"
              placeholder="请选择状态"
              size="mini"
              style="width: 180px"
              filterable
              clearable
              @change="statusChange"
            >
              <el-option
                v-for="item in ruleFormSelect.statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
          <div
            class="form-item"
            style="margin-left: 8px; margin-right: 56px; margin-bottom: 10px"
          >
            <span class="form-item-label">日间类型：</span>
            <el-select
              v-model="ruleForm.bedType"
              placeholder="请选择类型"
              size="mini"
              style="width: 180px"
              filterable
              clearable
              @change="statusChange"
            >
              <el-option
                v-for="item in bedTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>

          <div
            class="form-item"
            style="margin-left: 8px; margin-right: 56px; margin-bottom: 10px"
          >
            <span class="form-item-label">来源类型：</span>
            <el-select
              v-model="ruleForm.sourceType"
              placeholder="请选择类型"
              size="mini"
              style="width: 180px"
              filterable
              clearable
            >
              <el-option
                v-for="item in sourceList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
        </div>
        <div class="query-reset-btn right-btn-container">
          <div
            v-for="(item, index) in buttonList"
            :key="index + '_'"
            class="form-item-btn"
          >
            <Button
              :type="item.type"
              :icon="item.icon"
              :loading="item.loading"
              @click="item.handlerClick"
              >{{ item.label }}</Button
            >
          </div>
        </div>
      </div>
    </Container>
    <!-- 条件筛选结束 -->

    <!-- 病员卡片区域开始 -->
    <Container class="main" :height="height">
      <div v-loading="loading" class="wrap" style="height: 100%">
        <div class="card-container">
          <Empty v-if="patientsList.length === 0" style="margin: 20px auto" />
          <template>
            <RjssPatientCard
              v-for="item in patientsList"
              :key="item.id"
              :patient-info="item"
              @click.native="checkDetail(item)"
              @contextmenu.prevent.native="rightClick($event, item)"
            />
          </template>

          <!-- 取消预约 -->
          <ul v-show="menuVisible" id="menu" class="menu" @mouseover="onleitve">
            <template v-if="curImpatientInfor.state == 1">
              <li
                class="menu__item"
                style="margin-top: 3px"
                @click.stop="delPatientBed(curImpatientInfor)"
              >
                <template>取消预约</template>
              </li>
              <li
                class="menu__item"
                style="margin-top: 3px"
                @click.stop="updatePatientBed(curImpatientInfor)"
              >
                <template>完成治疗</template>
              </li>
            </template>

            <li
              class="menu__item"
              style="margin-top: 3px"
              @click.stop="printCertificate(curImpatientInfor)"
            >
              <template>住院证打印</template>
            </li>
          </ul>
        </div>
        <div style="text-align: right; padding: 8px 0 0 0">
          <el-pagination
            :current-page.sync="currentPage"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="pageSize"
            layout="prev, pager, next, sizes, total"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </Container>
    <!-- 病员卡片区域结束 -->
  </ContainerGroup>
</template>

<script>
import PatientCard from "./children/PatientCard.vue";
import RjssPatientCard from "./children/rjssPatientCard.vue";
import { getVYqBrdjxxRJSSDownLoad } from "@/utils/apis/rjbf";
import {
  getVYqBrdjxxRJSSPagesInfo,
  getRJSSVYqBrdjxx,
  delPatientBed,
  updatePatientBed,
} from "../../utils/apis/rjbf";

export default {
  name: "",
  components: {
    PatientCard,
    RjssPatientCard,
  },
  data() {
    return {
      curImpatientInfor: {},
      menuVisible: false, // 右键点击
      // 按钮列表
      buttonList: [
        {
          label: "查询",
          type: "primary",
          icon: "search",
          handlerClick: this.handlerSearch,
          loading: false,
        },
        {
          label: "重置",
          type: "info",
          icon: "reset",
          handlerClick: this.handlerReset,
        },
        {
          label: "导出",
          type: "info",
          icon: "export",
          handlerClick: this.handlerExport,
        },
        {
          label: "设置",
          type: "primary",
          icon: "set",
          handlerClick: this.handlerSet,
        },
      ],
      // 院区选中
      yard: "1",
      // 科室列表
      departmentList: [],
      // 当前选中科室索引值
      currentIndex: 0,
      // 查询表单（数据）
      ruleForm: {
        timeDate: "",
        status: 1,
        patientName: "",
        registerStatus: "",
        ycyDate: "",
        cyDate: "",
        bedType: "1",
        sourceType: "0",
      },
      // 状态
      ruleFormSelect: {
        statusOptions: [
          {
            label: "已预约",
            value: 1,
          },
          {
            label: "已完成",
            value: 2,
          },
        ],
        registerStatusOptions: [
          {
            label: "未登记",
            value: "0",
          },
          {
            label: "已登记",
            value: "1",
          },
        ],
      },
      bedTypeList: [
        {
          label: "日间手术",
          value: "1",
        },
        {
          label: "院前准备",
          value: "2",
        },
        {
          label: "日间输注",
          value: "4",
        },
      ],
      sourceList: [
        {
          label: "全部",
          value: "0",
        },
        {
          label: "住院",
          value: "1",
        },
        {
          label: "门诊",
          value: "2",
        },
      ],
      showCloseAndOpen: true,
      openOrCloseText: "展开",
      containerHeight: "28px",
      height: "fill",
      // 病人列表
      patientsList: [],
      loading: false,
      total: 0,
      pageNum: 1,
      pageSize: 20,
      currentPage: 1,
      deptCode: null,
      preid: "",
      patientsCount: "",
      itemRyzt: "",
      medicalInsuranceFlag: null,
      medicalType: null,
      name: null,
    };
  },
  mounted() {
    this.getTime();
    this._getData()
  },
  methods: {
    getTime() {
      const nowdays = new Date();
      nowdays.setTime(nowdays.getTime());
      const year = nowdays.getFullYear();
      const month = nowdays.getMonth() + 1;
      const myDate = nowdays.getDate();
      const monthnum = month >= 10 ? "" : "0";
      const datenum = myDate >= 10 ? "" : "0";
      const startDate =
        year + "-" + monthnum + month + "-" + datenum + myDate + " 00:00:00";
      const endDate =
        year + "-" + monthnum + month + "-" + datenum + myDate + " 23:59:00";
      this.ruleForm.timeDate = [startDate, endDate];
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this._getData();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.loading = true;
      this._getData();
    },
    _getData() {
      const params = {
        deptCode: this.deptCode,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        startTime:
          this.ruleForm.timeDate === "" || this.ruleForm.timeDate === null
            ? ""
            : this.ruleForm.timeDate[0],
        endTime:
          this.ruleForm.timeDate === "" || this.ruleForm.timeDate === null
            ? ""
            : this.ruleForm.timeDate[1],
        preOutStartTime: this.ruleForm.ycyDate && this.ruleForm.ycyDate[0],
        preOutEndTime: this.ruleForm.ycyDate && this.ruleForm.ycyDate[1],
        outStartTime: this.ruleForm.cyDate && this.ruleForm.cyDate[0],
        outEndTime: this.ruleForm.cyDate && this.ruleForm.cyDate[1],
        bedType: this.ruleForm.bedType,
        sourceType: this.ruleForm.sourceType,
        yard: this.yard,
        state: this.ruleForm.status,
        name: this.ruleForm.patientName,
        registerCode: this.ruleForm.registerStatus,
      };
      getVYqBrdjxxRJSSPagesInfo(params).then((res) => {
        if (res.data.code === 200) {
          this.patientsList = res.data.data.list;
          this.total = res.data.data.total;
          this.loading = false;
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    printCertificate(row) {
      let routeUrl = this.$router.resolve({
        path: "/ManualElecHosptalCertificate/certificate",
        query: { preid: row.preid, idCard: row.idenno, deptCode: row.deptCode },
      });
      window.open(routeUrl.href, "_blank");
    },
    delPatientBed(row) {
      this.$confirm({
        content: "是否确认取消预约？",
        title: "温馨提示",
        okFn: (res) => {
          delPatientBed({
            id: row.id,
            operName: ''
          })
            .then((res) => {
              if (res.data.code == 200) {
                this.$message.success("操作成功");
                this.menuVisible = false;
                this._getData();
              } else {
                this.$message.error("操作失败");
              }
            })
            .catch((error) => {
              this.$message.error("操作失败");
            });
        },
      });
    },
    updatePatientBed(row) {
      this.$confirm({
        content: "是否确认该用户完成治疗？",
        title: "温馨提示",
        okFn: (res) => {
          updatePatientBed(row.id)
            .then((res) => {
              if (res.data.code == 200) {
                this.$message.success("操作成功");
                this.menuVisible = false;
                this._getData();
              } else {
                this.$message.error("操作失败");
              }
            })
            .catch((error) => {
              this.$message.error("操作失败");
            });
        },
      });
    },
    _getExportData() {
      const params = {
        deptCode: this.deptCode,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        startTime:
          this.ruleForm.timeDate === "" || this.ruleForm.timeDate === null
            ? ""
            : this.ruleForm.timeDate[0],
        endTime:
          this.ruleForm.timeDate === "" || this.ruleForm.timeDate === null
            ? ""
            : this.ruleForm.timeDate[1],
        bedType: this.ruleForm.bedType,
        sourceType: this.ruleForm.sourceType,
        yard: this.yard,
        state: this.ruleForm.status,
        name: this.ruleForm.patientName,
        registerCode: this.ruleForm.registerStatus,
      };

      getVYqBrdjxxRJSSDownLoad(params).then((res) => {
        // if (res.data.code === 200) {
        const blob = new Blob([res.data]);
        const fileName = "患者信息" + ".xlsx";
        const URL = window.URL || window.webkitURL || window.moxURL;
        if ("download" in document.createElement("a")) {
          // 非IE下载
          const elink = document.createElement("a");
          elink.download = fileName; // 命名下载名称
          elink.style.display = "none";
          elink.href = URL.createObjectURL(blob); // 表示一个指定的file对象或Blob对象
          document.body.appendChild(elink);
          elink.click(); // 点击触发下载
          URL.revokeObjectURL(elink.href); // 释放URL 对象
          document.body.removeChild(elink);
        } else {
          // IE10+下载
          navigator.msSaveBlob(blob, fileName);
        }
        // }
      });
    },
    // 状态改变触发
    statusChange(val) {},
    // 查询功能
    handlerSearch() {
      this.pageNum = 1;
      this._getData();
    },
    // 重置搜索表单
    handlerReset(val) {
      this.getTime();
      this.ruleForm.ycyDate = "";
      this.ruleForm.cyDate = "";
      this.ruleForm.patientName = "";
      this.ruleForm.bedType = "1";
      this.ruleForm.sourceType = "0";
      this.ruleForm.status = 1;
      this._getData();
    },
    handlerExport(val) {
      this._getExportData();
    },
    handlerSet() {
      this.$router.push({
        path: "/dayBedCenter/set",
        // query: { pageNum: this.$route.query.pageNum }
      });
    },
    // 科室选择区域 -> 展开收起功能
    openAndCloseFilterForm() {
      this.containerHeight = this.openOrCloseText === "展开" ? "auto" : "28px";
      this.openOrCloseText = this.openOrCloseText === "展开" ? "收起" : "展开";
    },
    changeDepartment(item, index) {
      // 判断 -> 加载选中样式 -> 默认选中全部
      this.currentIndex = index;

      this.deptCode = item.deptCode;
      // 更改查询条件
      this._getData();
    },
    checkDetail(row) {
      this.$router.push({
        name: "dayPrepareDetail",
        params: {
          preid: row.preid,
          patientName: row.name,
        },
        query: {
          preid: row.preid,
          patientName: row.name,
        },
      });
    },
    // 鼠标移上去高亮
    onleitve() {
      var lis = document.getElementsByTagName("li");
      for (let i = 0; i < lis.length; i++) {
        lis[i].onmouseover = function() {
          this.style.color = "#217DFA";
        };
        lis[i].onmouseout = function() {
          this.style.color = "#555555";
        };
      }
    },
    // 取消小框框
    btn1() {
      this.menuVisible = false;
    },
    // 取消预约确定按钮
    btn(row) {
      const content = `<div style="word-break:break-all;width:386px">确定取消该预约吗？</div>`;
      this.$confirm({
        content: content,
        title: "确认信息",
        okFn: (res) => {
          const params = {
            id: this.curImpatientInfor.id,
          };
          delPatientBed(params).then((res) => {
            if (res.data.code === 200) {
              this.$message.success("成功取消预约！");
              // this.$router.go(0);
              this.handlerSearch();
            } else {
              this.$message.error("取消预约失败");
            }
          });
        },
        cancelFn: (res) => {},
      });
    },
    // 右键取消预约
    rightClick(MouseEvent, item) {
      if (!item.state) {
        return;
      }
      this.curImpatientInfor = item;
      this.preid = item.preid;
      this.itemRyzt = item.ryzt;
      this.medicalType = item.yblx;
      this.medicalInsuranceFlag = item.medicalInsuranceFlag;
      this.name = item.name;
      this.menuVisible = true;
      var menu = document.querySelector("#menu");
      if (MouseEvent.screenX < 100) {
        menu.style.left = MouseEvent.clientX + "px";
        menu.style.top = MouseEvent.clientY + "px";
      }
      if (MouseEvent.screenX > 100) {
        menu.style.left = MouseEvent.clientX + 4 + "px";
        menu.style.top = MouseEvent.clientY + 7 + "px";
      }
      document.addEventListener("click", this.foo);
    },
    foo() {
      // 取消鼠标监听事件 菜单栏
      this.menuVisible = false;
      document.removeEventListener("click", this.foo); // 要及时关掉监听，不关掉的是一个坑，不信你试试，虽然前台显示的时候没有啥毛病，加一个alert你就知道了
    },
  },
};
</script>

<style lang="less" scoped>
.container.tab-bar {
  margin-top: 0;
  padding: 0 10px 5px 10px;
}
/deep/ .el-tabs__header.is-top {
  margin-bottom: 0;
}
/deep/ .el-tabs__nav-wrap::after {
  background-color: #fff;
}
.query-main {
  display: flex;
  .label {
    flex: 0 0 76px;
    padding-top: 2px;
    margin-right: 32px;
  }
  .item-box {
    flex: 1 1 auto;
    margin: 0;
    display: flex;
    flex-wrap: wrap;
    .dpt-btn {
      cursor: pointer;
      padding: 2px 8px;
      margin-bottom: 12px;
      margin-right: 12px;
    }
    .dpt-btn:hover {
      background-color: #2165f9;
      color: #fff;
      border-radius: 3px;
      transition: 0.4s;
    }
  }
}
.department {
  border-bottom: 1px dashed #ccc;
  padding-bottom: 10px;
  overflow: hidden;
  // .label{
  //   flex-grow: 2;
  // }
  .btn-area {
    flex: 0 0 76px;
    padding-top: 2px;
    margin-left: 32px;
    text-align: right;
    padding-right: 3px;
    span {
      cursor: pointer;
      color: #217dfa;
    }
    i {
      color: #217dfa;
    }
  }
}
.query-box {
  padding-top: 10px;
  .query-reset-btn {
    width: 180px;
  }
}
/deep/ .el-input {
  width: 180px;
}
.right-btn-container {
  text-align: center;
  display: flex;
  justify-content: flex-end;
  padding-top: 5px;
  .form-item-btn {
    margin: 0px 3px;
  }
  .more-text {
    display: block;
    width: 50px;
    margin-top: 6px;
    color: #2165f9;
    cursor: pointer;
    user-select: none;
  }
}
.container.main {
  overflow-y: auto;
  .card-container {
    width: 100%;
    margin: 0 auto;
    display: flex;
    flex-wrap: wrap;
  }
}
.patient-card {
  margin: 16px;
}
.selected {
  background-color: #2165f9;
  color: #fff;
  border-radius: 3px;
}
/deep/ .el-tabs__item:hover {
  color: #2165f9;
}
/deep/ .el-tabs__item.is-active {
  color: #2165f9;
}
.menu {
  height: auto;
  width: 90px;
  position: absolute;
  z-index: 99;
  padding-inline-start: 0px;
  border-radius: 5px;
  box-shadow: 0px 3px 7px 0px rgba(199, 199, 199, 0.35);
  border: 1px solid #eeeeee;
  background-color: #ffffff;
  .menu__item {
    display: block;
    height: 43px;
    line-height: 43px;
    text-align: center;
    font-size: 14px;
    color: #555555;
    cursor: pointer;
    //   border: 1px solid #eeeeee;
    // background-color: #ffffff;
  }
}
.change-style {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
